package com.atguigu.edu.controller.front;

import com.atguigu.commonUtils.JwtUtils;
import com.atguigu.commonUtils.R;
import com.atguigu.commonUtils.orderVo.CourseWebVoOrder;
import com.atguigu.edu.entity.Course;
import com.atguigu.edu.entity.chapter.ChapterVo;
import com.atguigu.edu.entity.frontVo.CourseFrontVo;
import com.atguigu.edu.entity.frontVo.CourseWebVo;
import com.atguigu.edu.feign.OrderClient;
import com.atguigu.edu.service.ChapterService;
import com.atguigu.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/edu/courseFront")
//@CrossOrigin
public class CourseFrontController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private OrderClient orderClient;

    /**
     * 带分页的条件查询课程信息
     *
     * @param page
     * @param limit
     * @return
     */
    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page, @PathVariable long limit, @RequestBody(required = false) CourseFrontVo courseFrontVo) {

        Page<Course> pageCourse = new Page<>(page, limit);

        Map<String, Object> map = courseService.getCourseFrontList(pageCourse, courseFrontVo);

        return R.ok().data(map);
    }

    /**
     * 查询页面课程详情的方法
     *
     * @param courseId
     * @return
     */
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {
        //根据课程id，编写sql语句，查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);

        //根据课程id 查询章节和小节
        List<ChapterVo> chapterVideoList = chapterService.getChapterVideoByCourseId(courseId);

        //根据课程id 和用户id 查询当前课程 是否已经购买
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (memberId != null) {
            Boolean result = orderClient.isBuyCourse(courseId, memberId);
            return R.ok().data("courseWebVo", courseWebVo).data("chapterVideoList", chapterVideoList).data("isBuy", result);
        }
        return R.ok().data("courseWebVo", courseWebVo).data("chapterVideoList", chapterVideoList);

    }

    /**
     * 根据课程ID 获取课程信息
     *
     * @param id
     * @return
     */
    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id) {
        CourseWebVo courseInfo = courseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(courseInfo, courseWebVoOrder);

        return courseWebVoOrder;
    }
}
